package com.kilman.logger.ssh;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.apache.tools.ant.taskdefs.optional.ssh.SSHExec;

public class SSHUtils {
    
    public static String runCommand(String command, long timeout, String host, String username, String password) throws IOException {
        
        File file = new File("sshoutput.txt");
        
        SSHExec exec = new SSHExec();
        exec.setCommand(command);
        exec.setUsername(username);
        exec.setPassword(password);
        exec.setHost(host);
        exec.setTrust(true);
        exec.setOutput(file);
        exec.setAppend(false);
        exec.setFailonerror(false);
        exec.setTimeout(timeout);

        exec.execute();
        
        return readFileAsString(file);
    }

    private static String readFileAsString(File file) throws IOException {
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(new FileReader(file));
        char[] buf = new char[1024];
        int numRead = 0;
        while ((numRead = reader.read(buf)) != -1) {
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            buf = new char[1024];
        }
        reader.close();
        return fileData.toString();
    }
    
}
